package com.shwread.android.qysw.activity.psychological;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.GlideUtil;
import com.NewActionHelp;
import com.ciko.code.base.BaseActicity;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.newui.activity.EvaluateWebActivity;
import com.shwread.android.qysw.bean.psychological.EvaluatingDetailBean;
import com.shwread.android.qysw10000229.R;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.List;


/**
 * 心理评测详情界面
 * Created by sss on 2017/10/10.
 */
public class EvaluatingDetailActivity extends BaseActicity {
    public static final int FREE_EVALUATING = 1;//体验评测
    public static final int PAY_EVALUATING = 2;//付费评测

    /**
     * 评测类型
     */
    private int qryType;
    private int questionnaireId;
    private EvaluatingDetailBean evaluatingDetailBean;
    private TextView tvEvaluatingDetailTitle;
    private TextView tvEvaluatingPriceTitle;
    private LinearLayout llEvaluatingDetailPrice;
    private TextView tvEvaluatingDetailPrice;
    private TextView tvEvaluatingDetailCrowdInfo;
    private TextView tvEvaluatingDetailIntroduction;
    private LinearLayout llChildQuestionnaires;
    private LinearLayout llEvaluatingSuit;
    private Button btEvaluatingDetailPay;
    /**
     * 动画页面
     */
    private RelativeLayout commonLoadingLayout;
    /**
     * 加载动画
     */
    private ImageView loadingImg;
    /**
     * 动画
     */
    private AnimationDrawable animationDrawable;
    private TextView tvOpenUp;
    /**
     * 是否为套餐内子评测
     */
    private boolean isChild;
    private Activity activity;
    private String isBuy;
    private Drawable imgOpen;
    private Drawable imgUp;

    @Override
    protected void initTopBar() {
        enableNavLeftImg();
        setTitle("心理评测");
        Intent intent = getIntent();
        qryType = intent.getIntExtra("qryType", -1);
        questionnaireId = intent.getIntExtra("questionnaireId", -1);
        isChild = intent.getBooleanExtra("isChild", false);
        isBuy = intent.getStringExtra("isBuy");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_evaluating_detail);
        activity = this;
    }

    @Override
    protected void initView() {
        tvEvaluatingDetailTitle = findViewByID(R.id.tv_evaluating_detail_title);
        tvEvaluatingPriceTitle = findViewByID(R.id.tv_evaluating_price_title);
        llEvaluatingDetailPrice = findViewByID(R.id.ll_evaluating_detail_price);
        tvEvaluatingDetailPrice = findViewByID(R.id.tv_evaluating_detail_price);
        tvEvaluatingDetailCrowdInfo = findViewByID(R.id.tv_evaluating_detail_crowd_info);
        tvEvaluatingDetailIntroduction = findViewByID(R.id.tv_evaluating_detail_introduction);
        llChildQuestionnaires = findViewByID(R.id.ll_evaluating_detail_child_questionnaires);
        llEvaluatingSuit = findViewByID(R.id.ll_evaluating_suit);
        btEvaluatingDetailPay = findViewByID(R.id.bt_evaluating_detail_pay);
        tvOpenUp = findViewByID(R.id.tv_open_up);

        loadingImg = findViewByID(R.id.common_loading__img);
        commonLoadingLayout = findViewByID(R.id.common_loading_layout);
    }

    @Override
    protected void initAdapter() {

    }

    @Override
    protected void initDates() {
        //加载动画
        commonLoadingLayout.setVisibility(View.VISIBLE);
        commonLoadingLayout.setEnabled(false);
        loadingImg.setBackgroundResource(R.drawable.home_progress);
        animationDrawable = (AnimationDrawable) loadingImg.getBackground();
        animationDrawable.start();
        NewActionHelp.getQuestionnaireInfoByQryType(this, qryType, questionnaireId, new GetQuestionnaireInfoByQryTypeHandler());
    }

    @Override
    protected void initListener() {
        tvOpenUp.setOnClickListener(this);
        btEvaluatingDetailPay.setOnClickListener(this);
        commonLoadingLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.bt_evaluating_detail_pay:
                if (qryType == FREE_EVALUATING) {//体验评测
                    Intent intent = new Intent(this, EvaluatingQuestionnaireDetailActivity.class);
                    intent.putExtra("queId", questionnaireId);
                    startActivity(intent);
                } else if (qryType == PAY_EVALUATING) {//付费评测
                    if (isChild && "y".equals(isBuy)) {
                        toWebActivity();
                        return;
                    }
                    if ("n".equals(evaluatingDetailBean.getIsBuy())) {//未购买
                        EvaluatingPayUtils.getInstance().pay(activity, evaluatingDetailBean, new EvaluatingPayUtils.Listener() {
                            @Override
                            public void CallBack() {
                                initDates();
                            }
                        });
                    } else {
                        toWebActivity();
                    }
                }
                break;
            case R.id.common_loading_layout://重新加载
                initDates();
                break;
            case R.id.tv_open_up://展开收起
                if (tvEvaluatingDetailIntroduction.getMaxLines() == 2) {//展开
                    tvOpenUp.setText("收起");
                    tvEvaluatingDetailIntroduction.setMaxLines(100);
                    tvOpenUp.setCompoundDrawables(null, null, imgUp, null);
                } else {//收起
                    tvOpenUp.setText("详情");
                    tvEvaluatingDetailIntroduction.setMaxLines(2);
                    tvOpenUp.setCompoundDrawables(null, null,  imgOpen, null);
                }
                break;
        }
    }

    /**
     * 跳转到三方评测界面
     */
    private void toWebActivity() {
        Intent intent = new Intent(this, EvaluateWebActivity.class);
        intent.putExtra("title", "心理测评");
        startActivity(intent);
    }

    private class GetQuestionnaireInfoByQryTypeHandler extends ObjectHttpResponseHandler<EvaluatingDetailBean> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.e("sss", "失败---" + responseString);
            if (animationDrawable != null && animationDrawable.isRunning()) {
                animationDrawable.stop();
            }
            commonLoadingLayout.setVisibility(View.VISIBLE);
            commonLoadingLayout.setEnabled(true);
            loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, EvaluatingDetailBean detailBean, String responseString) {
            Log.e("sss", "成功---" + responseString);
            if (animationDrawable != null && animationDrawable.isRunning()) {
                animationDrawable.stop();
            }
            commonLoadingLayout.setVisibility(View.GONE);
            if (detailBean == null) {
                return;
            }
            evaluatingDetailBean = detailBean;
            setData();
        }

        @Override
        public Type getType() {
            return new TypeToken<EvaluatingDetailBean>() {
            }.getType();
        }
    }

    /**
     * 填充数据
     */
    private void setData() {
        tvEvaluatingDetailTitle.setText(evaluatingDetailBean.getTitle());
        tvEvaluatingDetailCrowdInfo.setText(evaluatingDetailBean.getCrowdInfo());
        setIntroduction(evaluatingDetailBean.getIntroduction());
        if (evaluatingDetailBean.getType() == 1) {//单独评测
            tvOpenUp.setVisibility(View.GONE);
            llEvaluatingSuit.setVisibility(View.GONE);
        } else {//套餐
            llEvaluatingSuit.setVisibility(View.VISIBLE);
            if (evaluatingDetailBean.getIntroduction().length() > 50) {
                openUpIntroduction();
            } else {
                tvOpenUp.setVisibility(View.GONE);
            }
            //填充子评测数据
            setChildList();
        }
        if (qryType == FREE_EVALUATING) {//体验评测
            btEvaluatingDetailPay.setBackgroundResource(R.drawable.action_btn);
            llEvaluatingDetailPrice.setVisibility(View.GONE);
            if (evaluatingDetailBean.getType() == 1) {//个人
                btEvaluatingDetailPay.setText("体验该评测");
            } else {//套餐
                btEvaluatingDetailPay.setText("体验该评测套餐");
            }
        } else if (qryType == PAY_EVALUATING) {//付费评测
            if ("n".equals(evaluatingDetailBean.getIsBuy())) {//未付款
                btEvaluatingDetailPay.setBackgroundResource(R.drawable.evaluating_buy_btn);
                llEvaluatingDetailPrice.setVisibility(View.VISIBLE);
                tvEvaluatingPriceTitle.setText("价格");
                tvEvaluatingPriceTitle.setTextColor(getResources().getColor(R.color.color_252525));
                tvEvaluatingDetailPrice.setText(String.format("¥%s", evaluatingDetailBean.getPrice()));

                if (evaluatingDetailBean.getType() == 1) {//个人
                    if (isChild) {
                        if ("y".equals(isBuy)) {
                            btEvaluatingDetailPay.setVisibility(View.VISIBLE);
                            btEvaluatingDetailPay.setBackgroundResource(R.drawable.action_btn);
                            btEvaluatingDetailPay.setText("测试该评测");
                        } else {
                            btEvaluatingDetailPay.setVisibility(View.GONE);
                        }
                    } else {
                        btEvaluatingDetailPay.setText("购买该评测");
                    }
                } else {//套餐
                    btEvaluatingDetailPay.setText("购买该评测套餐");
                }
            } else {//已付款
                tvEvaluatingDetailPrice.setText("");
                btEvaluatingDetailPay.setBackgroundResource(R.drawable.action_btn);
                tvEvaluatingPriceTitle.setText("已购买");
                tvEvaluatingPriceTitle.setTextColor(getResources().getColor(R.color.text_black_4));
                if (evaluatingDetailBean.getType() == 1) {//个人
                    btEvaluatingDetailPay.setText("测试该评测");
                } else {//套餐
                    btEvaluatingDetailPay.setText("测试该评测套餐");
                }
            }
        }
    }

    /**
     * 简介展开收起功能
     */
    private void openUpIntroduction() {
        tvEvaluatingDetailIntroduction.setMaxLines(2);
        tvOpenUp.setText("详情");
        imgOpen = getResources().getDrawable(R.drawable.img_evaluating_detail_open);
        imgUp = getResources().getDrawable(R.drawable.img_evaluating_detail_up);
        imgOpen.setBounds(0, 0, imgOpen.getMinimumWidth(), imgOpen.getMinimumHeight());
        imgUp.setBounds(0, 0, imgUp.getMinimumWidth(), imgUp.getMinimumHeight());
        tvOpenUp.setCompoundDrawables(null, null, imgOpen, null);
    }

    private void setIntroduction(CharSequence sequence) {
        SpannableStringBuilder span = new SpannableStringBuilder("占位").append(sequence);
        span.setSpan(new ForegroundColorSpan(Color.TRANSPARENT), 0, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);//前两位设为透明色
        tvEvaluatingDetailIntroduction.setText(span);//简介
    }

    /**
     * 设置子评测列表
     */
    private void setChildList() {
        List<EvaluatingDetailBean.ChildQuestionnairesBean> childQuestionnaires = evaluatingDetailBean.getChildQuestionnaires();
        if (childQuestionnaires != null) {
            View view;
            if (llChildQuestionnaires.getChildCount() != 0) {
                llChildQuestionnaires.removeAllViews();
            }
            LayoutInflater layoutInflater = LayoutInflater.from(llChildQuestionnaires.getContext());
            for (EvaluatingDetailBean.ChildQuestionnairesBean childQuestionnaire : childQuestionnaires) {
                view = layoutInflater.inflate(R.layout.item_evaluating_list, llChildQuestionnaires, false);
                TextView tv = (TextView) view.findViewById(R.id.tv_evaluating_title);
                tv.setText(childQuestionnaire.getTitle());
                GlideUtil.filletedCornerLoad(this, childQuestionnaire.getImgUrl(), 8, (ImageView) view.findViewById(R.id.img_evaluating_cover));
                final int questionnaireId = childQuestionnaire.getQuestionnaireId();
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toEvaluatingDetail(questionnaireId);
                    }
                });
                llChildQuestionnaires.addView(view);
            }
        }
    }

    /**
     * 跳转到子评测详情
     */
    private void toEvaluatingDetail(int questionnaireId) {
        Intent intent = new Intent(this, EvaluatingDetailActivity.class);
        intent.putExtra("qryType", qryType);
        intent.putExtra("questionnaireId", questionnaireId);
        intent.putExtra("isChild", true);
        intent.putExtra("isBuy", evaluatingDetailBean.getIsBuy());
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NewActionHelp.cancel(this);
        if (animationDrawable != null && animationDrawable.isRunning()) {
            animationDrawable.stop();
        }
    }
}